package br.com.cfccultura.admin.model.dao.mysql;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import br.com.cfccultura.admin.model.dao.ISalaAulaDAO;
import br.com.cfccultura.admin.model.enums.Ativo;
import br.com.cfccultura.admin.model.vo.Sala;

@Repository
public class SalaAulaDAO extends DAO implements ISalaAulaDAO {

	@Override
	public List<Sala> consultar(Sala vo) {

		String sql = "SELECT cd_sala_aula, dc_sala_aula, qt_aluno, id_ativo FROM tb_sala_aula where ";
		Object[] params;
		if(vo.getCodigo() != null) {
			sql += "cd_sala_aula = ? ";
			params = new Object[]{vo.getCodigo()};
		} else {
			sql += "dc_sala_aula like ? ";
			String desc = "%";
			if(vo.getDescricao() != null && !vo.getDescricao().equals("")) {
				desc = vo.getDescricao() + "%";
			}
			params = new Object[]{desc};
		}
		sql += "and id_ativo = 1 order by dc_sala_aula";

		List<Sala> result = query(sql, params, new RowMapper<Sala>() {
			@Override
			public Sala mapRow(ResultSet rs, int arg1) throws SQLException {
				Sala vo = new Sala();
				vo.setCodigo(rs.getInt("cd_sala_aula"));
				vo.setDescricao(rs.getString("dc_sala_aula"));
				vo.setQtdeAluno(rs.getInt("qt_aluno"));
				vo.setAtivo(Ativo.setValue(rs.getInt("id_ativo")));
				return vo;
			}
			
		});		
		
		return result;
	}
	
	@Override
	public void incluir(Sala vo) {
		String sql = "INSERT INTO tb_sala_aula(dc_sala_aula, qt_aluno) values(?,?)";
		update(sql, new Object[] {vo.getDescricao(), vo.getQtdeAluno()});
	}
	
	@Override
	public void alterar(Sala vo) {
		String sql = "UPDATE tb_sala_aula set dc_sala_aula = ?, qt_aluno = ? where cd_sala_aula = ?";
		update(sql, new Object[] {vo.getDescricao(), vo.getQtdeAluno(), vo.getCodigo()});
	}
	
	@Override
	public void excluir(Integer id) {
		try {
			String sql = "DELETE FROM tb_sala_aula where cd_sala_aula = ?";
			update(sql, new Object[] {id});
		} catch(DataIntegrityViolationException e) {
			String sql = "UPDATE tb_sala_aula set id_ativo = 0 where cd_sala_aula = ?";
			update(sql, new Object[] {id});
		}
	}

}
